package com.jh.paymentchannel.service;

import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jh.paymentchannel.pojo.XJYCoinRegister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.xjy.Base64Util;
import com.jh.paymentchannel.util.xjy.KeyGenerator;
import com.jh.paymentchannel.util.xjy.PlatService;

import cn.jh.common.utils.DateUtil;
import net.sf.json.JSONObject;


@Service
public class XJYCoinTopupRequest implements TopupRequest {

	private static final Logger log = LoggerFactory.getLogger(XJYCoinTopupRequest.class);

	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;

	@Autowired
	private BranchbankBussiness branchbankBussiness;

	@Autowired
	private Util util;

	@Value("${payment.ipAddress}")
	private String ipAddress;

	@Value("${xjycoin.publickey}")
	private String PublicKey;

	@Value("${xjycoin.appid}")
	private String appId;
	
	//private String PublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHd3HpKMRcIkx83Oz3YkQjw7JMgLQ5ZnQXjUAwmAZ6FVlYSPNMKQY7oCY7O9wQo/kOtjmjngIDh6biMVT70eMuNhpl6B0TOyw3v2FqswqhjvNno6LoKWl2la+/O8tHYYDQE4+ncBApCWzMfj7xIqJENElOExnxEqtTlHehv/JxYQIDAQAB";

	//private String appId = "989d801a0544427093be120f11e36f52";

	private String mermodifyUrl = "http://39.106.15.18/openapi/api/unionpay/integral/dzero/mer/innet/modify";

	private static final Charset UTF_8 = StandardCharsets.UTF_8;

	private String version = "1.0.1";

	private String channelType = "88";

	@Override
	public Map<String, String> topupRequest(HttpServletRequest request, String amount, String ordercode,
			String orderdesc, String extra, String notifyurl, String returnurl, String channelParam) throws Exception {

		Map<String, String> map = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "没有该订单信息");
			return map;
		}
		String realamount = resultObj.getString("realAmount");
		String userid = resultObj.getString("userid");
		// 银行卡
		String bankCard = resultObj.getString("bankcard");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费用
		String extraFee = resultObj.getString("extraFee");
		
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}

		if (resultObj.isNullObject()) {

			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "没有结算卡");
			return map;
		}

		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		/** 身份证号 */
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		// 银行名称
		String bankName = resultObj.getString("bankName");

		String cardType = resultObj.getString("cardType");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		if (resultObj == null) {
			return null;
		}

		String cardName = resultObj.getString("bankName");
		String cardtype = resultObj.getString("cardType");

		String expiredTime = resultObj.getString("expiredTime");
		String securityCode = resultObj.getString("securityCode");

		XJYCoinRegister xjyCoinRegisterByPhoneAndBankCard = topupPayChannelBusiness
				.getXJYCoinRegisterByPhoneAndBankCard(phone, cardNo);

		if (null == xjyCoinRegisterByPhoneAndBankCard) {
			log.info("用户需要进件======");

			map.put("resp_code", "success");
			map.put("channel_type", "jf");
			map.put("redirect_url",
					ipAddress + "/v1.0/paymentchannel/topup/toxjycoinbankinfo?bankName="
							+ URLEncoder.encode(bankName, "UTF-8") + "&bankNo=" + cardNo + "&amount=" + amount
							+ "&ordercode=" + ordercode + "&cardType=" + URLEncoder.encode(cardType, "UTF-8")
							+ "&ipAddress=" + ipAddress + "&bankCard=" + bankCard + "&cardName="
							+ URLEncoder.encode(cardName, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
							+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=0");
			return map;

		} else {
			if(!rate.equals(xjyCoinRegisterByPhoneAndBankCard.getRate()) || !extraFee.equals(xjyCoinRegisterByPhoneAndBankCard.getExtraFee()) || !cardNo.equals(xjyCoinRegisterByPhoneAndBankCard.getBankCard())) {
				boolean updateXJYCoinQuickRate = updateXJYCoinQuickRate(ordercode);
				if(updateXJYCoinQuickRate) {
					
					if (null == topupPayChannelBusiness.getXJYCoinBindCardByBankCard(bankCard)) {
						log.info("用户需要绑卡======");

						map.put("resp_code", "success");
						map.put("channel_type", "jf");
						map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/toxjycoinbankinfo?bankName="
								+ URLEncoder.encode(bankName, "UTF-8") + "&bankNo=" + cardNo + "&amount=" + amount
								+ "&ordercode=" + ordercode + "&cardType=" + URLEncoder.encode(cardType, "UTF-8")
								+ "&ipAddress=" + ipAddress + "&bankCard=" + bankCard + "&cardName="
								+ URLEncoder.encode(cardName, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
								+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=1");
						return map;

					} else {
						log.info("发起交易======");

						map.put("resp_code", "success");
						map.put("channel_type", "jf");
						map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/toxjycoinbankinfo?bankName="
								+ URLEncoder.encode(bankName, "UTF-8") + "&bankNo=" + cardNo + "&amount=" + amount
								+ "&ordercode=" + ordercode + "&cardType=" + URLEncoder.encode(cardType, "UTF-8")
								+ "&ipAddress=" + ipAddress + "&bankCard=" + bankCard + "&cardName="
								+ URLEncoder.encode(cardName, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
								+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=2");
						return map;

					}

					
				}else {
					map.put("resp_code", "failed");
					map.put("channel_type", "jf");
					map.put("resp_message", "亲，网络出错啦");
					return map;
					
				}
				
			}else {
				
				if (null == topupPayChannelBusiness.getXJYCoinBindCardByBankCard(bankCard)) {
					log.info("用户需要绑卡======");

					map.put("resp_code", "success");
					map.put("channel_type", "jf");
					map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/toxjycoinbankinfo?bankName="
							+ URLEncoder.encode(bankName, "UTF-8") + "&bankNo=" + cardNo + "&amount=" + amount
							+ "&ordercode=" + ordercode + "&cardType=" + URLEncoder.encode(cardType, "UTF-8")
							+ "&ipAddress=" + ipAddress + "&bankCard=" + bankCard + "&cardName="
							+ URLEncoder.encode(cardName, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
							+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=1");
					return map;

				} else {
					log.info("发起交易======");

					map.put("resp_code", "success");
					map.put("channel_type", "jf");
					map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/toxjycoinbankinfo?bankName="
							+ URLEncoder.encode(bankName, "UTF-8") + "&bankNo=" + cardNo + "&amount=" + amount
							+ "&ordercode=" + ordercode + "&cardType=" + URLEncoder.encode(cardType, "UTF-8")
							+ "&ipAddress=" + ipAddress + "&bankCard=" + bankCard + "&cardName="
							+ URLEncoder.encode(cardName, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
							+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=2");
					return map;

				}
			}
			
			
		}

	}

	// 修改费率
	public boolean updateXJYCoinQuickRate(String ordercode) throws Exception {

		log.info("进入修改费率接口=======");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONObject resultObj = jsonObject.getJSONObject("result");

		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费用
		String extraFee = resultObj.getString("extraFee");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);

		jsonObject = JSONObject.fromObject(result);
		resultObj = jsonObject.getJSONObject("result");

		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		String bankName = resultObj.getString("bankName");
		String phone = resultObj.getString("phone"); // 预留信用卡手机号码
		String idcard = resultObj.getString("idcard");// 身份证号
		String userName = resultObj.getString("userName");// 用户姓名

		XJYCoinRegister xjyCoinRegisterByBankCard = topupPayChannelBusiness.getXJYCoinRegisterByBankCard(cardNo);

		Map<String, String> paramsMap = new HashMap<String, String>();

		paramsMap.put("appId", appId);
		paramsMap.put("channelType", channelType);
		paramsMap.put("version", version);
		paramsMap.put("orderId", ordercode);// 订单号
		paramsMap.put("txnTime", DateUtil.getyyyyMMddHHmmssDateFormat(new Date()));
		paramsMap.put("toAccNo", cardNo);// 收款卡号
		paramsMap.put("phoneNo", phone);// 预留手机号
		paramsMap.put("toBankName", bankName);// 银行名称
		paramsMap.put("toAccType", "PERSONNEL");// 银行卡类型
		paramsMap.put("realName", userName);// 姓名
		paramsMap.put("identityNo", idcard);// 身份证号
		paramsMap.put("t0DrawRate", rate);// 交易扣率
		String t0DrawFee = new BigDecimal(extraFee).multiply(new BigDecimal("100")).setScale(0).toString();
		paramsMap.put("t0DrawFee", t0DrawFee);// 单笔手续费(单位:分)
		paramsMap.put("insCode", xjyCoinRegisterByBankCard.getInsCode());// 入网编号

		Map<String, String> reqData = new HashMap<String, String>();
		try {
			reqData.put("data", Base64Util.encode(
					KeyGenerator.encryptByPublicKey(JSON.toJSONString(paramsMap).getBytes(UTF_8), PublicKey)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		String requestUrl = String.format(mermodifyUrl + "/" + channelType + "/" + appId, channelType, appId);
		String jsonString;
		boolean istrue = false;
		try {
			jsonString = PlatService.postAsString(reqData, requestUrl, UTF_8);
			JSONObject json = jsonObject.fromObject(jsonString);
			String success = json.getString("success");
			String msg = json.getString("msg");
			// JSONObject attributes = json.getJSONObject("attributes");
			// String insCode = attributes.getString("insCode");

			log.info("jsonString====" + jsonString);
			log.info("json====" + json);
			log.info("success====" + success);
			log.info("msg====" + msg);
			// log.info("attributes====" + attributes);
			// log.info("insCode====" + insCode);

			if ("true".equals(success) && "SUCCESS".equalsIgnoreCase(msg)) {
				log.info("请求修改进件信息接口成功===================");

				XJYCoinRegister xjyCoinRegister = topupPayChannelBusiness.getXJYCoinRegisterByPhoneAndBankCard(phone,
						cardNo);
				xjyCoinRegister.setPhone(phone);
				xjyCoinRegister.setBankCard(cardNo);
				xjyCoinRegister.setIdCard(idcard);
				xjyCoinRegister.setRate(rate);
				xjyCoinRegister.setExtraFee(extraFee);

				istrue = true;
				try {
					topupPayChannelBusiness.createXJYCoinRegister(xjyCoinRegister);
				} catch (Exception e) {
					return istrue;
				}

				return istrue;
			} else {

				return istrue;
			}

		} catch (Exception e) {
			log.error("请求修改进件接口有误===" + e);
			return istrue;
		}

	}

}
